import { IpcMainInvokeEvent } from 'electron'

/**
 * 统一响应格式
 */
export interface StandardResponse<T = any> {
  code: number        // 状态码：200=成功，400=客户端错误，500=服务器错误
  data?: T           // 响应数据
  message: string    // 响应消息
  timestamp: number  // 时间戳
}

/**
 * 状态码常量
 */
export const ResponseCode = {
  SUCCESS: 200,           // 成功
  CREATED: 201,           // 创建成功
  BAD_REQUEST: 400,       // 请求错误
  NOT_FOUND: 404,         // 资源不存在
  CONFLICT: 409,          // 冲突（如重复创建）
  INTERNAL_ERROR: 500,    // 内部错误
  DATABASE_ERROR: 501,    // 数据库错误
  VALIDATION_ERROR: 502,  // 验证错误
  FILE_ERROR: 503         // 文件操作错误
} as const

/**
 * 项目相关类型
 */
export interface ProjectData {
  id?: string
  name: string
  description?: string
  resolution?: { width: number; height: number }
  frameRate?: number
  duration?: number
  thumbnail?: string
  filePath?: string
  metadata?: any
}

export interface ProjectCreateRequest {
  name: string
  templateId?: string
  resolution?: { width: number; height: number }
  frameRate?: number
}

export interface ProjectOpenRequest {
  id?: string
  path?: string
}

export interface ProjectSaveRequest {
  id: string
  data?: Partial<ProjectData>
}

export interface ProjectExportRequest {
  id: string
  format: 'mp4' | 'gif' | 'webm'
  options: {
    quality?: number
    fps?: number
    resolution?: { width: number; height: number }
    startFrame?: number
    endFrame?: number
  }
}

/**
 * 资源相关类型
 */
export interface AssetImportRequest {
  files: string[]
  projectId?: string
}

export interface AssetListRequest {
  type?: 'image' | 'audio' | 'video' | 'all'
  projectId?: string
}

export interface AssetData {
  id: string
  name: string
  type: 'image' | 'audio' | 'video'
  path: string
  size: number
  duration?: number
  resolution?: { width: number; height: number }
  thumbnail?: string
  metadata?: any
}

/**
 * 系统相关类型
 */
export interface SystemInfoRequest {}

export interface SystemInfoResponse {
  platform: string
  arch: string
  version: string
  memory: {
    total: number
    free: number
    used: number
  }
  cpu: {
    model: string
    cores: number
    usage: number
  }
}

/**
 * 用户相关类型
 */
export interface UserLoginRequest {
  email: string
  password: string
}

export interface UserRegisterRequest {
  email: string
  password: string
  username: string
}

export interface UserData {
  id: string
  email: string
  username: string
  avatar?: string
  subscription?: {
    type: 'free' | 'pro' | 'enterprise'
    expiresAt?: Date
  }
}

/**
 * IPC通道定义（使用标准响应格式）
 */
export interface IPCChannels {
  // 项目相关
  'project:create': { request: ProjectCreateRequest; response: StandardResponse<ProjectData> }
  'project:open': { request: ProjectOpenRequest; response: StandardResponse<ProjectData> }
  'project:save': { request: ProjectSaveRequest; response: StandardResponse<boolean> }
  'project:delete': { request: { id: string }; response: StandardResponse<boolean> }
  'project:list': { request: {}; response: StandardResponse<ProjectData[]> }
  'project:getAll': { request: {}; response: StandardResponse<ProjectData[]> }
  'project:export': { request: ProjectExportRequest; response: StandardResponse<{ path: string }> }

  // 资源相关
  'asset:import': { request: AssetImportRequest; response: StandardResponse<AssetData[]> }
  'asset:list': { request: AssetListRequest; response: StandardResponse<AssetData[]> }
  'asset:delete': { request: { id: string }; response: StandardResponse<boolean> }

  // 系统相关
  'system:info': { request: SystemInfoRequest; response: StandardResponse<SystemInfoResponse> }
  'system:openDialog': { request: { type: 'file' | 'directory'; filters?: any[] }; response: StandardResponse<{ paths: string[]; canceled: boolean }> }
  'system:showSaveDialog': { request: { defaultPath?: string; filters?: any[] }; response: StandardResponse<{ path?: string; canceled: boolean }> }

  // 用户相关
  'user:login': { request: UserLoginRequest; response: StandardResponse<UserData> }
  'user:register': { request: UserRegisterRequest; response: StandardResponse<UserData> }
  'user:logout': { request: {}; response: StandardResponse<boolean> }
  'user:profile': { request: {}; response: StandardResponse<UserData | null> }

  // 应用相关
  'app:version': { request: {}; response: StandardResponse<string> }
  'app:quit': { request: {}; response: StandardResponse<void> }
  'app:minimize': { request: {}; response: StandardResponse<void> }
  'app:maximize': { request: {}; response: StandardResponse<void> }
  'app:close': { request: {}; response: StandardResponse<void> }
}

/**
 * 类型安全的IPC处理器类型
 */
export type IPCHandler<T extends keyof IPCChannels> = (
  event: IpcMainInvokeEvent,
  args: IPCChannels[T]['request']
) => Promise<IPCChannels[T]['response']>

/**
 * IPC错误类型
 */
export class IPCError extends Error {
  constructor(
    message: string,
    public code: string,
    public details?: any
  ) {
    super(message)
    this.name = 'IPCError'
  }
}

/**
 * IPC响应包装器
 */
export interface IPCResponse<T = any> {
  success: boolean
  data?: T
  error?: {
    message: string
    code: string
    details?: any
  }
}

/**
 * 创建标准成功响应
 */
export function createStandardResponse<T>(
  data: T,
  message: string = '操作成功',
  code: number = ResponseCode.SUCCESS
): StandardResponse<T> {
  return {
    code,
    data,
    message,
    timestamp: Date.now()
  }
}

/**
 * 创建标准错误响应
 */
export function createStandardErrorResponse(
  message: string,
  code: number = ResponseCode.INTERNAL_ERROR,
  data?: any
): StandardResponse {
  return {
    code,
    data,
    message,
    timestamp: Date.now()
  }
}

/**
 * 创建成功响应（保持向后兼容）
 */
export function createSuccessResponse<T>(data: T): IPCResponse<T> {
  return {
    success: true,
    data
  }
}

/**
 * 创建错误响应（保持向后兼容）
 */
export function createErrorResponse(error: Error | IPCError | string): IPCResponse {
  if (typeof error === 'string') {
    return {
      success: false,
      error: {
        message: error,
        code: 'UNKNOWN_ERROR'
      }
    }
  }

  if (error instanceof IPCError) {
    return {
      success: false,
      error: {
        message: error.message,
        code: error.code,
        details: error.details
      }
    }
  }

  return {
    success: false,
    error: {
      message: error.message,
      code: 'INTERNAL_ERROR',
      details: error.stack
    }
  }
}
